//
//  DownloadOperationManager.m
//  06-随机下载图片
//
//  Created by apple on 16/1/8.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "DownloadOperationManager.h"

@interface DownloadOperationManager ()

/// 队列
@property (nonatomic, strong) NSOperationQueue *queue;
/// 操作缓存池
@property (nonatomic, strong) NSMutableDictionary *operationCache;
/// 图片内存缓存
@property (nonatomic, strong) NSMutableDictionary *imageCache;

@end

@implementation DownloadOperationManager

- (NSOperationQueue *)queue
{
    if (_queue == nil) {
        _queue = [[NSOperationQueue alloc] init];
    }
    return _queue;
}

- (NSMutableDictionary *)operationCache
{
    if (_operationCache == nil) {
        _operationCache = [[NSMutableDictionary alloc] init];
    }
    return _operationCache;
}

- (NSMutableDictionary *)imageCache
{
    if (_imageCache == nil) {
        _imageCache = [[NSMutableDictionary alloc] init];
    }
    return _imageCache;
}

+ (instancetype)sharedManager
{
    static DownloadOperationManager *manager;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DownloadOperationManager alloc] init];
    });
    return manager;
}

- (void)downloadWithURLString:(NSString *)URLString finishedBlock:(void (^)(UIImage *))finishedBlock
{
    // 判断某个下载存不存在,如果存在直接继续下载
    if ([self.operationCache objectForKey:URLString] != nil) {
        return;
    }
    
    // 判断有没有缓存
    if ([self checkCacheWith:URLString]) {
        
        // 回调
        finishedBlock([self.imageCache objectForKey:URLString]);
        
        return;
    }
    
    // 建立下载操作.// 从模型去地址
    DownloaderOperation *op = [DownloaderOperation downloaderOperationWithURLString:URLString finishedBlock:^(UIImage *image) {
        // 断言
        NSAssert(finishedBlock != nil, @"单例下载完成之后的回调 finishedBlock 不能为空");
        
        // 单例回调下载完成的图片
        finishedBlock(image);
        
        // 保存图片到内存中
        [self.imageCache setObject:image forKey:URLString];
        
        // 下载完成之后,将操作从操作缓存池移除
        [self.operationCache removeObjectForKey:URLString];
    }];
    // 保存下载操作
    [self.operationCache setObject:op forKey:URLString];
    // 将操作添加到队列
    [self.queue addOperation:op];
}

/// 判断有没有缓存
- (BOOL)checkCacheWith:(NSString *)URLString
{
    // 判断内存缓存
    if ([self.imageCache objectForKey:URLString] != nil) {
        NSLog(@"从内存中加载...");
        return YES;
    }
    
    // 判断沙盒缓存
    NSData *data = [NSData dataWithContentsOfFile:[URLString appendCache]];
    UIImage *image = [UIImage imageWithData:data];
    if (image != nil) {
        NSLog(@"从沙盒中加载...");
        // 保存一份在内存中
        [self.imageCache setObject:image forKey:URLString];
        
        return YES;
    }
    
    return NO;
}

- (void)cancelOperationWithLastURL:(NSString *)lastURL
{
    // 判断是否是第一次执行
    // 如果是第一次执行lastURL为空,操作缓存池内部也是为空的,就不需要执行取消
    if (lastURL != nil) {
        [[self.operationCache objectForKey:lastURL] cancel];
    }
}

@end
